package middlewares

import (
	"fmt"
	"net/http"
	"time"

	"github.com/dgrijalva/jwt-go"
	"github.com/gin-gonic/gin"
)

const token = "eyJhbGciOiJSUzUxMiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1MTYyMzkwODIsImlhdCI6MTUxNjIzOTAyMiwiaXNzIjoiY29vbGNhci9hdXRoIiwic3ViIjoiOTUyNiJ9.GmHHvkXE5rA-UDvo-eO-HQ3ti5cQiphACOZR1o4ClN71bAxax8De6yMsktiL73Czi0JWrJCds1QwbvPk3qmA70y2YbwGmJx93yZNvu9ypbVwPNhJWXdlYy4UdWAmlQml92YauQM6GmXXQ-Dz0QU75XGYBP_Zz2vtHseTySfkyBS4uqpzmflXc9ixFLqzkYdqSwXvQwlHip3EjcQ6EKjSDft1mn-KFA-5wwQiKvCnmDK4_BFhfT9hWKXonv5FyXvL6WAhjIUVh-BJo5QeyPjnv5X0GSGLmJqoV3aws5SlIf0hjZNgeYsZq0nF5wg0O8WQrK2kMCZZauK_RWeIgpQsRg"
const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAjjuSjF9NbtPEXHzwnd15
rspFl1N686BENnwC9Zume02ulAJIjfRStpq4RE8LFUjGTd9JG/x+qVI9QcuSJ/b+
fiyTkdLGtu7BCkFSUyO/Dat6b2Y/l2rprjEVVR7CwByuYMPXP8K9W//+mGtmW+FK
vqaRutI9l8EZHDguaetrVsBD5y6zTWDeJBiCA8nyA1qp/PaaY2qCZQg4RAaUKjia
JHECY2LekSBxqQa4+yZ1FeBXygsx4BueVrZJ26j35poNpGN7AcHqZTih4ySlNInM
5toD27oMhzejfFihFC6Uil2fVnaoElLhKAamwGIOlhEvW5Di26Ss3gLhJyahKRX9
CwIDAQAB
-----END PUBLIC KEY-----
`

func AuthVerify(c *gin.Context) {
	c.GetHeader("Authorization") // 从请求头获取token信息

	jwt.TimeFunc = func() time.Time {
		return time.Unix(1516239022, 0)
	}

	pubKey, _ := jwt.ParseRSAPublicKeyFromPEM([]byte(publicKey))

	t, err := jwt.ParseWithClaims(token, &jwt.StandardClaims{}, func(t *jwt.Token) (interface{}, error) {
		return pubKey, nil
	})
	if err != nil {
		fmt.Println("err", err)
		// 过期的话会在这里报错
		c.JSON(http.StatusUnauthorized, gin.H{
			"msg": "登录参数失效",
		})
		c.Abort()
		return
	}

	if !t.Valid {
		c.JSON(http.StatusUnauthorized, gin.H{
			"msg": "token不合法",
		})
		c.Abort()
		return
	}

	claim, ok := t.Claims.(*jwt.StandardClaims)
	if !ok {
		c.JSON(http.StatusUnauthorized, gin.H{
			"msg": "token不是标准的claim",
		})
		c.Abort()
		return
	}

	if err := claim.Valid(); err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{
			"msg": "claim 不合法",
		})
		c.Abort()
		return
	}

	//fmt.Println("Issuer", claim.Issuer)
	//fmt.Println("claim", claim)
	//fmt.Println("IssuedAt", claim.IssuedAt)
	//fmt.Println("ExpiresAt", claim.ExpiresAt)
	//fmt.Println("Subject", claim.Subject)
	c.Set("accountID", claim.Subject)
	c.Next()
}
